<template>
  <div class="assignment-area">
    <!-- 作业栏标题 -->
    <h2 class="title">作业栏</h2>

    <!-- 作业表格 -->
    <div class="assignment-table">
      <el-table :data="tableData" stripe>
        <el-table-column label="作业Id" prop="id" />
        <el-table-column label="作业名称" prop="name" />
        <el-table-column label="截止日期" prop="deadline" />
        <el-table-column label="文件">
          <template #default="scope">
            <span>{{ scope.row.file }}</span>
            <button class="download-btn" @click="handleDownload(scope.row.id)">下载</button>
          </template>
        </el-table-column>

        <!-- 新增上传作业栏 -->
        <el-table-column label="上传作业">
          <template #default="scope">
            <input 
              type="file" 
              :id="`fileInput_${scope.row.id}`" 
              @change="handleFileChange($event, scope.row.id)" 
              style="display: none" 
            />
            <button class="select-file-btn" @click="handleSelectFile(scope.row.id)">选择文件</button>
            <button class="upload-btn" @click="handleUpload(scope.row.id)">上传作业</button>
          </template>
        </el-table-column>

        <!-- 显示互评状态 -->
        <el-table-column label="互评状态">
          <template #default="scope">
            <div>
              <el-tag v-if="scope.row.isMutual === 'true'" type="success">已设置互评</el-tag>
              <el-tag v-else type="info">未设置互评</el-tag>
            </div>
            <div v-if="scope.row.isMutual === 'true'">
              <button class="review-btn" @click="navigateToReview(scope.row.id)">进入互评</button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:8085';

const router = useRouter();
const tableData = ref([]);
const selectedFiles = ref({});  // 存储每个作业对应的文件

// 获取作业数据的函数
const fetchHomeworkData = async (courseId) => {
  try {
    const response = await axios.get('/homework/viewhomeworkitem', {
      params: { courseId }
    });

    tableData.value = response.data.map(item => ({
      id: item.homeworkId,
      name: item.title,
      deadline: item.deadLine,
      file: item.fileName,
      isMutual: item.isMutual || 'false',
    }));
  } catch (error) {
    console.error('获取作业数据失败:', error);
  }
};

onMounted(() => {
  const courseId = 1; // 替换为实际的 courseId
  fetchHomeworkData(courseId);
});

// 跳转到互评页面
const navigateToReview = (homeworkId) => {
  router.push({ name: 'MutualReview', params: { homeworkId } });
};

// 选择文件
const handleSelectFile = (homeworkId) => {
  const input = document.querySelector(`#fileInput_${homeworkId}`);
  if (input) {
    input.click();
  }
};

// 处理文件选择
const handleFileChange = (event, homeworkId) => {
  selectedFiles.value[homeworkId] = event.target.files[0];
};

// 上传作业
const handleUpload = async (homeworkId) => {
  const file = selectedFiles.value[homeworkId];
  if (!file) {
    alert("请先选择文件！");
    return;
  }

  const formData = new FormData();
  formData.append('file', file);
  formData.append('homeworkId', homeworkId);
  formData.append('userId', 1); // 替换为实际 userId

  try {
    const response = await axios.post('/homework/submithomework', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    console.log('上传成功:', response.data);
  } catch (error) {
    console.error('上传作业失败:', error);
  }
};
</script>

<style scoped>
.review-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.review-btn:hover {
  background-color: #e68a00;
}
</style>
